package com.yonyou.pmclouds.statistic.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.yonyou.pmclouds.ApplicationConsts;
import com.yonyou.pmclouds.basecom.entity.PageObject;
import com.yonyou.pmclouds.basecom.exception.BusinessException;
import com.yonyou.pmclouds.basecom.runtime.RuntimeEnvironment;
import com.yonyou.pmclouds.outter.enterprise.EnterpriseInfoQuery;
import com.yonyou.pmclouds.outter.tenant.TenantInfoQuery;
import com.yonyou.pmclouds.outter.user.UserInfoQuery;
import com.yonyou.pmclouds.statistic.entity.*;
import com.yonyou.pmclouds.statistic.rmiitf.ActivityStatisticsService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Collections;
import java.util.Comparator;
import java.util.List;

@RestController
@RequestMapping({"/activityStatistic", "/mobile/activityStatistic"})
public class ActivityStatisticController {
    @Reference(version = ApplicationConsts.APPLICATION_VERSION)
    private ActivityStatisticsService service;
    @Autowired
    private EnterpriseInfoQuery enterpriseInfoQuery;
    @Autowired
    private UserInfoQuery userInfoQuery;
    @Autowired
    private TenantInfoQuery tenantQuery;

    @GetMapping("/info")
    public OrgActivityStatisticsViewVOs activityInfo(@RequestParam(value = "tenantId", required = false) String tenantId,
                                                     @RequestParam(value = "orgId", required = false) String orgId,
                                                     @RequestParam(name = "limit", defaultValue = "3") Integer limit,
                                                     @RequestParam("start") long timeStart, @RequestParam("end") long timeEnd) throws BusinessException {
        // TODO 校验组织权限
        // TODO 校验租户和组织的关系
        if (StringUtils.isEmpty(tenantId)) {
            tenantId = RuntimeEnvironment.getTenantId();
        }
        OrgActivityStatisticsViewVOs result = service.queryActivityInfo(tenantId, orgId, limit, timeStart, timeEnd);
        userInfoQuery.tranUserInfoField(result.getProjects(), new String[]{"projectManager"}, new String[]{"projectManagerName"});
        return result;
    }

    @GetMapping("/orgOrders")
    public Object tenantOrgList(@RequestParam(value = "tenantId", required = false) String tenantId,
                                @RequestParam(name = "orgKeyword", required = false) String orgKeyword,
                                @RequestParam(name = "start", defaultValue = "0") Integer start,
                                @RequestParam(name = "limit", defaultValue = "50") Integer limit,
                                @RequestParam("timeStart") long timeStart, @RequestParam("timeEnd") long timeEnd) throws BusinessException {
        if (StringUtils.isEmpty(tenantId)) {
            tenantId = RuntimeEnvironment.getTenantId();
        }
        final PageObject<?> orgActivityInfo = service.queryOrgActivityOrder(tenantId, orgKeyword, start, limit, timeStart, timeEnd);
        final OrgActivityStatisticsViewVOs tenantInfo = service.queryActivityInfo(tenantId, null, 0, timeStart, timeEnd);
        // 可能存在租户下没有组织的情况
        if (orgActivityInfo == null)
            return null;
        Object[] t = orgActivityInfo.getObjects();
        if (ArrayUtils.isNotEmpty(t)) {
            for (Object obj : t) {
                TenantActivityStatisticVO info = (TenantActivityStatisticVO) obj;
                if (info.getPkOrg() == null) {
                    info.setOrgName(tenantQuery.queryTenantInfoById(tenantId).getTenantName());
                    break;
                }
            }
        }
        final String finalTenantId = tenantId;
        return new Object() {
            public final PageObject<?> orgInfo = orgActivityInfo;
            public final int picCount = tenantInfo.getPicCount();
            public final int billCount = tenantInfo.getBillCount();
            public final String tenant = finalTenantId;
        };
    }

    @GetMapping("/order")
    public PageObject projectActivityOrder(@RequestParam(value = "tenantId", required = false) String tenantId,
                                           @RequestParam(value = "orgId", required = false) String orgId,
                                           @RequestParam(value = "keyword", required = false) String keyword,
                                           @RequestParam("timeStart") long timeStart, @RequestParam("timeEnd") long timeEnd,
                                           @RequestParam(value = "start", defaultValue = "0") Integer pageStart,
                                           @RequestParam(value = "limit", defaultValue = "20") Integer limit) throws BusinessException {
        // TODO 校验组织权限
        // TODO 校验租户和组织的关系
        if (StringUtils.isEmpty(tenantId)) {
            tenantId = RuntimeEnvironment.getTenantId();
        }
        PageObject pageObject = service.queryProjectActivityOrder(tenantId, orgId, keyword, pageStart, limit, timeStart, timeEnd);
        userInfoQuery.tranUserInfoField(pageObject.getObjects(), new String[]{"projectManager"}, new String[]{"projectManagerName"});
        return pageObject;
    }

    @GetMapping("/projectBillType")
    public ProjectBillTypeCountVO[] projectBillTypeCount(@RequestParam(value = "tenantId", required = false) String tenantId, @RequestParam("projectId") String projectId,
                                                         @RequestParam("timeStart") long timeStart, @RequestParam("timeEnd") long timeEnd) {
        return service.queryCountOfProjectBillType(tenantId, projectId, timeStart, timeEnd);
    }

    @GetMapping("/detail")
    public ActivityPenetrateVO activityDetail(@RequestParam(value = "tenantId", required = false) String tenantId,
                                              @RequestParam(value = "orgId", required = false) String orgId,
                                              @RequestParam("start") long timeStart, @RequestParam("end") long timeEnd) throws BusinessException {
        if (StringUtils.isEmpty(tenantId)) {
            tenantId = RuntimeEnvironment.getTenantId();
        }
        if (StringUtils.isEmpty(tenantId) || StringUtils.isEmpty(orgId))
            throw new BusinessException("未获取到当前租户和组织");
        ActivityPenetrateVO activityPenetrateVO = service.queryActivityDetail(tenantId, orgId, timeStart, timeEnd);

        if (activityPenetrateVO == null) return new ActivityPenetrateVO();

        if (activityPenetrateVO.getConstructCountList() != null) {
            enterpriseInfoQuery.tranEntInfoField(activityPenetrateVO.getConstructCountList().toArray(new ActivityCountVO[0]), new String[]{ActivityCountVO.PK_ACTIVITY},
                    new String[]{ActivityCountVO.ACTIVITY_NAME});
        }

        if (activityPenetrateVO.getSupervisorCountList() != null) {
            enterpriseInfoQuery.tranEntInfoField(activityPenetrateVO.getSupervisorCountList().toArray(new ActivityCountVO[0]), new String[]{ActivityCountVO.PK_ACTIVITY},
                    new String[]{ActivityCountVO.ACTIVITY_NAME});
        }

        if (activityPenetrateVO.getOwnEntCountList() != null) {
            enterpriseInfoQuery.tranEntInfoField(activityPenetrateVO.getOwnEntCountList().toArray(new ActivityCountVO[0]), new String[]{ActivityCountVO.PK_ACTIVITY},
                    new String[]{ActivityCountVO.ACTIVITY_NAME});
        }

        if (activityPenetrateVO.getOwnerCountList() != null) {
            userInfoQuery.tranUserInfoField(activityPenetrateVO.getOwnerCountList().toArray(new ActivityCountVO[0]), new String[]{ActivityCountVO.PK_ACTIVITY},
                    new String[]{ActivityCountVO.ACTIVITY_NAME});
        }
        return activityPenetrateVO;
    }

    @GetMapping("/entPersonRank")
    public MemberCountVO[] enterprisePersonRankInOrg(@RequestParam(value = "tenantId", required = false) String tenantId,
                                                     @RequestParam(value = "orgId") String orgId,
                                                     @RequestParam(value = "entId") String entId,
                                                     @RequestParam("timeStart") long timeStart, @RequestParam("timeEnd") long timeEnd,
                                                     @RequestParam(value = "start", defaultValue = "0") Integer pageStart,
                                                     @RequestParam(value = "limit", defaultValue = "20") Integer limit) throws BusinessException {
        if (StringUtils.isEmpty(tenantId)) {
            tenantId = RuntimeEnvironment.getTenantId();
        }
        MemberCountVO[] memberCountVOS = service.queryEntPersonRankInOrg(tenantId, orgId, entId, timeStart, timeEnd, pageStart, limit);
        userInfoQuery.tranUserInfoField(memberCountVOS, new String[]{"memberId"}, new String[]{"memberName"});
        if (ArrayUtils.isEmpty(memberCountVOS))
            return memberCountVOS;

        // 排序
        for (MemberCountVO countVO : memberCountVOS) {
            List<MemberCountVO.ProjectCount> projectCounts = countVO.getProjectCounts();
            if (CollectionUtils.isEmpty(projectCounts))
                continue;

            Collections.sort(projectCounts, new Comparator<MemberCountVO.ProjectCount>() {
                @Override
                public int compare(MemberCountVO.ProjectCount o1, MemberCountVO.ProjectCount o2) {
                    return o1.getBillCount() - o2.getBillCount();
                }
            });
        }

        return memberCountVOS;
    }
}
